package com.demo.web;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.demo.config.DirectReceiver;
import com.demo.config.MqSender;
import com.demo.entity.MqFailInfo;
import com.demo.mapper.MqFailInfoMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;


@Slf4j
@Api(description = "MQ相关")
@RestController
@RequestMapping("/api")
public class MQController  {


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MqSender mqSender;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private MqFailInfoMapper mqFailInfoMapper;

    @ApiOperation(value = "获取所有错误数据")
    @GetMapping(value = "/allErrorMq")
    public Object allErrorMq() {
        List<MqFailInfo> mqFailInfos = mqFailInfoMapper.selectList(new EntityWrapper<MqFailInfo>().eq("status", 0)
        );
        return mqFailInfos;
    }

    /**
     *
     * @return
     */
    @ApiOperation(value = "根据id推送错误消息到原始队列")
    @GetMapping(value = "/pushQueueById")
    public Object pushQueueById(String id) {
        MqFailInfo mqFailInfo = mqFailInfoMapper.selectById(id);
        if(mqFailInfo != null){
            String messageId = mqFailInfo.getMessageId();
            int indexOf = messageId.lastIndexOf("-");
            String mqId = messageId.substring(indexOf + 1);
            mqSender.sendNoRepeat(mqFailInfo.getExchangeName(), mqFailInfo.getRoutingKey(), mqFailInfo.getBody(), mqId);
            mqFailInfo.setStatus(1);
            mqFailInfoMapper.updateById(mqFailInfo);
        } else {
            return "fail";
        }
        return "success";
    }

}

